---------------------------------------------------------------
-- @Description：         config handler
---------------------------------------------------------------
local skynet = require "skynet"
local log = require "sky_log"
local cc = require "sky_call"
local uu = require "sky_utils"
local json = require "json"


local M = {}

--============================= Local Function =============================--
local function load_ini(filename)
    local data = {}
    local session = nil
    local file = io.open(filename, "r")
    if not file then
        return
    end

    for line in file:lines() do
        line = string.sub(line, 1, (string.find(line, "#") or string.find(line, ";") or (string.len(line) + 1)) - 1)
        if line ~= "" then
            --session
            local s = line:match("%[(.+)%]")
            if s then 
                session = s
            elseif session then 
                --find '='
                local epos = string.find(line, "=") 
                if epos and (epos ~= 1) and (epos ~= string.len(line)) then
                    if data[session] == nil then                
                        data[session] = {}
                    end
                    data[session][string.sub(line, 1, epos - 1)] = string.sub(line, epos + 1)
                end
            end
        end
    end

    file:close()

    return data
end

local function fill_config_data(plat_config, plat_config_raw, plat_table_config, plat_id)
    if plat_config_raw then 
        plat_config[plat_id] = {}
        plat_config[plat_id].config = {}
        plat_config[plat_id].config.plat_id = plat_id
        --memdb
        plat_config[plat_id].config.mem_db_server_port = (plat_config_raw[plat_id].MemdbServer or {}).MEMDBPORT
        plat_config[plat_id].config.mem_db_server_ip = (plat_config_raw[plat_id].MemdbServer or {}).MEMDBHOST
        --memcache
        plat_config[plat_id].config.memcache_uid = (plat_config_raw[plat_id].MemCached or {}).MEMCACHEDHOST_MID
        plat_config[plat_id].config.memcache_signup = (plat_config_raw[plat_id].MemCached or {}).MEMCACHEDHOST_SIGNUP
        plat_config[plat_id].config.memcache_exp = (plat_config_raw[plat_id].MemCached or {}).MEMCACHEDHOST_EXP
        plat_config[plat_id].config.memcache_tid = (plat_config_raw[plat_id].MemCached or {}).MEMCACHEDHOST_TID
        --mysql
        plat_config[plat_id].config.mysql_db = (plat_config_raw[plat_id].GameServer or {}).DB
        plat_config[plat_id].config.mysql_host = (plat_config_raw[plat_id].GameServer or {}).HOST
        plat_config[plat_id].config.mysql_password = (plat_config_raw[plat_id].GameServer or {}).PARSSWORD
        plat_config[plat_id].config.mysql_port = (plat_config_raw[plat_id].GameServer or {}).PORT
        plat_config[plat_id].config.mysql_user = (plat_config_raw[plat_id].GameServer or {}).USER
        plat_config[plat_id].config.mysql_socket = (plat_config_raw[plat_id].GameServer or {}).SOCKET
        --redis
        plat_config[plat_id].config.redis_ext_host = (plat_config_raw[plat_id].MemCached or {}).REDISHOST_EXT
        plat_config[plat_id].config.redis_ext_passwd = (plat_config_raw[plat_id].MemCached or {}).REDISHOST_EXT_PASSWD
        plat_config[plat_id].config.redis_tid_host = (plat_config_raw[plat_id].MemCached or {}).REDISHOST_TID
        plat_config[plat_id].config.redis_tid_passwd = (plat_config_raw[plat_id].MemCached or {}).REDISHOST_TID_PASSWD
        plat_config[plat_id].config.redis_gi_host = (plat_config_raw[plat_id].MemCached or {}).REDISHOST_GI
        plat_config[plat_id].config.redis_gi_passwd = (plat_config_raw[plat_id].MemCached or {}).REDISHOST_GI_PASSWD
        plat_config[plat_id].config.redis_lottery_host = (plat_config_raw[plat_id].MemCached or {}).REDISHOST_LOTTERY
        plat_config[plat_id].config.redis_lottery_passwd = (plat_config_raw[plat_id].MemCached or {}).REDISHOST_LOTTERY_PASSWD
        plat_config[plat_id].config.need_auth = (plat_config_raw[plat_id].MemCached or {}).IF_REDIS_AUTH

        --同时初始化好桌子表
        plat_table_config[plat_id] = {}
        log.warning("fill_config_data success: ".. plat_id)
    end
end

local function fill_tablelist(plat_config, plat_table_config)
    local server_id = tonumber(skynet.getenv("boyaa_srv_id"))
    if not server_id then
        log.error("fill_tablelist no server_id!")
        return 
    end

    local sql = "call GetTableList("..server_id..")"
    local sql_ret = cc.call_mysql("call_sql", tonumber(plat_config.config.plat_id), sql)
    --log.info("sql_ret[1]=", sql_ret[1])
    if sql_ret and sql_ret[1] then
        for _, v in pairs(sql_ret[1]) do
            local one_table = {}
            one_table.id = v.tid
            one_table.name = v.tname
            one_table.rule = v.rule
            one_table.small_blind = v.tblindmin
            one_table.buy_min = v.tbuymin
            one_table.buy_max = v.tbuymax
            one_table.player_max = v.tplayermax
            one_table.plogname = v.plogname
            one_table.bid = v.bid
            one_table.auto_stand = v.autoStand
            one_table.vote_time = v.voteTime
            one_table.kick_wait_time = v.kickwaittime
            one_table.Venuecosts = v.Venuecosts
            one_table.is_addr = v.IsAddr
            one_table.chipin_time = v.chipinTime
            one_table.max_num = v.maxnum
            one_table.ttype = v.ttype
            one_table.tvip = v.tvip
            one_table.texprate = v.texprate
            one_table.IpMax = v.IpMax
            one_table.autobuy = v.autobuy
            one_table.forbid_kick = v.forbidKick
            one_table.deduct = v.deduct
            one_table.prechip = v.prechip
            one_table.tvip = v.tvip
            one_table.anti = v.Allprechip   --前注
            one_table.standtimer = v.standtimer
            one_table.limitcondition = v.limitcondition
            one_table.privateRoom = v.privateRoom
            one_table.tstatus = v.tstatus
            one_table.tpostion = v.tpostion
            one_table.pumprate = v.pumprate
            one_table.pot_limit = v.pot_limit
            one_table.tattr = v.tattr
            
            if one_table.tattr
            and type(one_table.tattr)=="string"
            and (one_table.tattr~='') then
                one_table.tattr_decode = json.decode(one_table.tattr)
            end

            if tonumber(one_table.id) then
                plat_table_config[tonumber(one_table.id)] = one_table
            end
        end
    end

    log.warning("fill_tablelist success!")
    --uu.write_read_file(table_list)
end

local function fill_mysql_data(plat_config, plat_table_config)
    if not plat_config 
    or not plat_config.config 
    or not plat_config.config.plat_id then 
        log.error("fill_mysql_data error : plat_config=", plat_config)
        return
    end

    cc.call_mysql("init_by_config", plat_config.config)

    fill_tablelist(plat_config, plat_table_config)
end

function M.init_config(service_config_self)
    --正式环境直接读对应平台配置项
    local the_plat_id = tonumber(skynet.getenv("the_plat_id"))
    if the_plat_id then
        service_config_self.plat_config_raw[the_plat_id] = load_ini("../room/service/config/Config_"..the_plat_id..".ini") 
    else
        local plat_ids = {
           13, 103, 124
        }
        for _, plat_id in pairs(plat_ids) do
            service_config_self.plat_config_raw[plat_id] = load_ini("/data/gameserver/Poker_"..plat_id.."/Config/Config.ini")
        end
    end

    --log.info("session=", service_config_self.plat_config_raw)
    for id, config_info in pairs(service_config_self.plat_config_raw) do
        log.warning("####################config "..id.." start####################")

        fill_config_data(service_config_self.plat_config, service_config_self.plat_config_raw, service_config_self.plat_table_config, tonumber(id))

        --mysql
        fill_mysql_data(service_config_self.plat_config[tonumber(id)], service_config_self.plat_table_config[tonumber(id)])
        --memcache
        --fill_memcache_data(self.plat_config[tonumber(plat_id)])
        --memdb
        --fill_memdb_data(self.plat_config[tonumber(plat_id)])
        --redis
        --fill_redis_data(self.plat_config[tonumber(plat_id)])

        log.warning("####################config "..id.." end####################")
    end
end

return M